package com.xp.basic.heima.nio.netty.simpledemo.chat.handler;

import com.xp.basic.heima.nio.netty.simpledemo.chat.message.RpcRequestMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.message.RpcResponseMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.service.HelloService;
import com.xp.basic.heima.nio.netty.simpledemo.chat.service.HelloServiceFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;
import java.util.Objects;

@ChannelHandler.Sharable
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        int squenceId = msg.getSquenceId();
        RpcResponseMessage rpcResponseMessage = new RpcResponseMessage();
        rpcResponseMessage.setSquenceId(squenceId);

        try{

            String interfaceName = msg.getInterfaceName();
            String methodName = msg.getMethodName();
            Class<?> clazz = Class.forName(interfaceName);
            Method method = clazz.getMethod(methodName, msg.getParameterTypes());
            Object invoke = method.invoke(clazz.newInstance(), msg.getParameterValue());
            if (Objects.nonNull(invoke)) {
                System.out.println(" 执行 rpc 之后为空 ");
            }
            rpcResponseMessage.setReturnValue(invoke);
            System.out.println("rpc 执行成功 ");
        }catch (Exception e){
            e.printStackTrace();
            String message = e.getCause().getMessage();
            rpcResponseMessage.setExceptionValue(new Exception("rpc error :"+message));
        }

        ctx.writeAndFlush(rpcResponseMessage);
    }
}
